var { mysql } = require('../qcloud')

// 获取组信息
module.exports = async (ctx, next) => {
    try {
        let totals = await mysql('cLog').sum('step as steps').select('groupid').groupBy('groupid')
        let groupMembers = await mysql('cMemberInfo').count('cMemberInfo.groupid as members').select('cMemberInfo.groupid', 'cGroup.groupname').innerJoin('cGroup', 'cMemberInfo.groupid', 'cGroup.groupid').groupBy('cMemberInfo.groupid')
        let res = []
        if (Array.isArray(totals) && Array.isArray(groupMembers)) {
            res = groupMembers.map(item => {
                let data = {
                    groupid: item.groupid,
                    groupname: item.groupname,
                    members: item.members,
                    avg: 0
                }
                totals.forEach(el => {
                    if (el.groupid === item.groupid) {
                        data.avg = parseInt(el.steps / item.members)
                    }
                })
                return data
            })
        }

        ctx.state.data = res
        ctx.state.code = 200
    } catch (error) {
        ctx.state.data = error
        ctx.state.code = 409
    }
}
